package com.sdp.khy.baotou.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.khy.baotou.db.khy_package.entity.KhyPackage;
import com.sdp.khy.baotou.db.khy_package.service.IKhyPackageService;
import com.sdp.khy.baotou.db.khy_user_invoice.entity.KhyUserInvoice;
import com.sdp.khy.baotou.db.khy_user_invoice.service.IKhyUserInvoiceService;
import com.sdp.khy.baotou.utils.KhyConstants;

@RestController
@RequestMapping("/KhyUserInvoiceController")
public class KhyUserInvoiceController {

	@Autowired
	private IKhyUserInvoiceService iKhyUserInvoiceService;
	
	@Autowired
	private IKhyPackageService iKhyPackageService;
	
	@Autowired
	private Query query;

	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iKhyUserInvoiceService, KhyUserInvoice.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody KhyUserInvoice userInvoice) {
		if(userInvoice==null) {
			return Result.error("信息为空");
		}
		if(StringUtils.isEmpty(userInvoice.getKeyId())) {
			userInvoice.setInvoiceStatus(KhyConstants.发票开具中状态.getCode());
			iKhyUserInvoiceService.save(userInvoice);
		}else {
			iKhyUserInvoiceService.updateById(userInvoice);
		}
		return Result.ok();
	}
	
	/**
	 * 开票
	 * @param userInvoice
	 * @return
	 */
	@PostMapping(value = "/Billing")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> Billing(@RequestBody KhyUserInvoice userInvoice) {
		if(userInvoice==null) {
			return Result.error("开票信息为空");
		}
		if(StringUtils.isEmpty(userInvoice.getKeyId())) {
			return Result.error("开票信息不存在");
		}
		if(StringUtils.isEmpty(userInvoice.getPackageId())) {
			return Result.error("快递信息不存在");
		}
		
		KhyPackage khyPackage = iKhyPackageService.queryKhyPackageById(userInvoice.getPackageId());
		if(khyPackage==null) {
			return Result.error("快递信息不存在");
		}
		khyPackage.setIsInvoice(KhyConstants.是.getCode());
		userInvoice.setInvoiceStatus(KhyConstants.发票开具完成状态.getCode());
		iKhyUserInvoiceService.updateById(userInvoice);
		iKhyPackageService.updateById(khyPackage);
		
		return Result.ok();
	}
	
}
